<?php

namespace Common\Channels;

use Hyperf\Context\Context;
use Hyperf\Redis\RedisFactory;

class TcpChannel
{
    /**
     * @var RedisFactory
     */
    private RedisFactory $redisFactory;

    public function __construct(RedisFactory $redisFactory)
    {
        $this->redisFactory = $redisFactory;
    }

    /**
     * 发送消息给指定的 TCP 客户端
     *
     * @param int $fd TCP 客户端的文件描述符
     * @param string $message 要发送的消息
     * @throws \RedisException
     */
    public function sendToTcpClient(int $fd, string $message): void
    {
        // 将消息和客户端文件描述符保存到上下文中
        Context::set('tcp_message', $message);
        Context::set('tcp_fd', $fd);

        // 将消息发送到 TCP 服务器的通道
        $redis = $this->redisFactory->get('default');
        $redis->publish('tcp_channel', $message);
    }
}
